package com.webserver.http;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpResponse {
    private int starusCode=200;
    private String statusReason="OK";
    private Map<String,String> headers=new HashMap<>();
    private Socket socket;
    private File entity;
    public HttpResponse(Socket socket){
        this.socket=socket;
    }
    public void flush() throws IOException {
        sendStatusLine();
        sendHeaders();
        sendContent();
    }
    public void sendStatusLine() throws IOException {
        String line="HTTP/1.1"+" "+starusCode+" "+statusReason;
        println(line);
    }
    public void sendHeaders() throws IOException {
        Set<Map.Entry<String,String>>entrySet=headers.entrySet();
        for(Map.Entry<String,String>e:entrySet){
            String name=e.getKey();
            String value=e.getValue();
            String line=name+": "+value;
            println(line);
        }
        println("");
    }
    public void sendContent() throws IOException {
        try (
        OutputStream out=socket.getOutputStream();
        ) {
            FileInputStream fis = new FileInputStream(entity);
            byte[] data = new byte[1024 * 10];
            int len;
            while ((len = fis.read(data)) != -1) {
                out.write(data, 0, len);
            }
            System.out.println("响应发送结束");
        }
    }

    public int getStarusCode() {
        return starusCode;
    }

    public void setStarusCode(int starusCode) {
        this.starusCode = starusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }
    public void println(String line) throws IOException {
        OutputStream out=socket.getOutputStream();
        byte[]data=line.getBytes("ISO8859-1");
        out.write(data);
        out.write(13);
        out.write(10);

    }
    public void putHeader(String name,String value){
        this.headers.put(name,value);
    }

    public File getEntity() {
        return entity;
    }

    public void setEntity(File entity) {
        this.entity = entity;
    }
}
